package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;

import java.net.InetAddress;
import java.net.UnknownHostException;

@SpringBootApplication
@RestController
public class DemoApplication implements ApplicationListener<WebServerInitializedEvent> {

	public static void main(String[] args) {
//		System.out.println(DemoApplication.getIP());
		SpringApplication.run(DemoApplication.class, args);
		System.out.println("Listening HTTP server on http://"+DemoApplication.getIP()+":"+serverPort);
		DemoApplication demo = new DemoApplication();
		System.out.println("Listening HTTP server on "+demo.getUrl());
	}

	private static int serverPort;
	@Override
	public void onApplicationEvent(WebServerInitializedEvent event){
		this.serverPort = event.getWebServer().getPort();
//		System.out.println(serverPort);
	}

	public  String getUrl(){
		InetAddress address = null;
		try {
			address = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return "http://"+address.getHostAddress()+":"+this.serverPort;
	}
	public static String getIP(){
		InetAddress address = null;
		try{
			address = InetAddress.getLocalHost();
		} catch (UnknownHostException e){
			e.printStackTrace();
		}
		return address.getHostAddress();
	}

	@GetMapping("/hello")
	public String hello(@RequestParam(value = "name", defaultValue = "world") String name) {
		return String.format("hello %s", name);
	}
	@GetMapping("/version")
	public String version(@RequestParam(value = "name", defaultValue = "World") String name) {
		return String.format("{\"version\": \"0.0.1\"}");
	}
	@GetMapping("/*")
	public String error(@RequestParam(value = "name", defaultValue = "World") String name) {
		return String.format("404 not found");
	}
}
